﻿using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Web.UI.WebControls;
using System.Collections.Generic;

namespace ISolutions.SharePoint.MuiManager.Layouts.ISolutions.SharePoint.MuiManager
{
    public partial class EditResource : DialogLayoutsPageBage
    {
        Dictionary<int, TextBox> textboxTranslation = new Dictionary<int, TextBox>();

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            foreach (MuiLanguage language in LanguageService.Instance.GetLanguages(SPContext.Current.Web))
            {
                CreateControlsForLanguage(language);
            }
        }

        private void CreateControlsForLanguage(MuiLanguage language)
        {
            TextBox textBox = new TextBox();
            textBox.ID = string.Format("Textbox_Translation_{0}", language.LanguageCode);
            textBox.CssClass= "ms-input";
            textboxTranslation.Add(language.LanguageCode, textBox);

            TableRow row = new TableRow();
            tableTranslation.Rows.Add(row);
            TableCell cellCaption = new TableCell();
            cellCaption.CssClass = "ms-formlabel";
            row.Cells.Add(cellCaption);
            cellCaption.Text = language.DisplayName;
            TableCell cellControl = new TableCell();
            cellControl.CssClass = "ms-formbody";
            row.Cells.Add(cellControl);
            cellControl.Controls.Add(textBox);
        }

        protected void buttonSave_Clicked(object sender, EventArgs e)
        {
            string urlRes = Page.Request.Params["RES"];
            if (!String.IsNullOrEmpty(urlRes))
            {
                MuiResource resource = MuiResourceService.GetMuiResource(urlRes);

                foreach (int languageCode in textboxTranslation.Keys)
                {
                    TextBox textbox = textboxTranslation[languageCode];
                    resource.SetResource(languageCode, textbox.Text);
                }
                resource.Save(SPContext.Current.Web);
            }

            
            base.EndOperation(1);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            string urlRes = Page.Request.Params["RES"];
            if (!String.IsNullOrEmpty(urlRes))
            {
                MuiResource resource = MuiResourceService.GetMuiResource(urlRes);

                if (!Page.IsPostBack)
                {
                    literalKey.Text = resource.Key;

                    foreach (int languageCode in textboxTranslation.Keys)
                    {
                        TextBox textbox = textboxTranslation[languageCode];
                        textbox.Text = resource.GetResource(languageCode);
                    }
                }
            }
        }
    }
}
